package com.mike.uaa.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.mike.uaa.core.DefaultAuthenticationToken;
import com.mike.uaa.core.GrantedAuthority;
import com.mike.uaa.core.User;

import java.io.IOException;
import java.time.format.DateTimeFormatter;

/**
 * @author z zhang
 */
public class DefaultAuthTokenSerializer extends JsonSerializer<DefaultAuthenticationToken> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void serialize(DefaultAuthenticationToken token, JsonGenerator jsonGen, SerializerProvider provider) throws IOException {
        jsonGen.writeStartObject();

        jsonGen.writeObjectFieldStart("user");
        User user = (User) token.getPrincipal();
        if (user != null) {
            if (user.getId() != null) {
                jsonGen.writeNumberField("id", user.getId());
            }
            if (user.getUsername() != null) {
                jsonGen.writeStringField("username", user.getUsername());
            }
            if (user.getNickname() != null) {
                jsonGen.writeStringField("nickname", user.getNickname());
            }
            if (user.getStatus() != null) {
                jsonGen.writeNumberField("status", user.getStatus());
            }
            if (user.getMobile() != null) {
                jsonGen.writeStringField("mobile", user.getMobile());
            }
            if (user.getLastLogin() != null) {
                jsonGen.writeStringField("lastLogin", formatter.format(user.getLastLogin()));
            }
        }
        jsonGen.writeEndObject();

        jsonGen.writeBooleanField("authenticated", token.isAuthenticated());
        jsonGen.writeNumberField("expiresIn", token.getExpiresIn());
        jsonGen.writeNumberField("issuedAt", token.getIssuedAt().toEpochMilli());
        jsonGen.writeStringField("tokenValue", token.getTokenValue());
        jsonGen.writeArrayFieldStart("authority");
        if (token.getAuthorities() != null) {
            for (GrantedAuthority authority : token.getAuthorities()) {
                jsonGen.writeString(authority.getAuthority());
            }
        }
        jsonGen.writeEndArray();
        jsonGen.writeEndObject();
    }
}
